package cn.wolfcode.shop.cloud.mq;

import cn.wolfcode.shop.cloud.ws.WebSocketServer;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
@RocketMQMessageListener(
        consumerGroup = MQConstants.SECKILL_CREATE_ORDER_NOTIFY_GROUP,
        topic = MQConstants.SECKILL_ORDER,
        selectorExpression = MQConstants.SECKILL_CREATE_SUCCESS_TAG+"||"+MQConstants.SECKILL_CREATE_FAIL_TAG
)
public class MQListener implements RocketMQListener<Map> {
    @Override
    public void onMessage(Map map) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        WebSocketServer socketServer = WebSocketServer.clients.get(map.get("uuid"));
        if(socketServer!=null){
            try {
                System.out.println("收到客户端通知: 开始发送结果到客户端");
                socketServer.getSession().getBasicRemote().sendText(JSON.toJSONString(map));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}